import { ResponseDataType } from '@/types/response'
import { reactive } from 'vue'

interface RemoteState<T = any> {
  data: T | undefined
  isLoading: boolean
}

interface RemoteHookWithParams<T = any, R = any> {
  state: RemoteState<T>,
  fetchData: (params: R) => Promise<void>
}

interface RemoteHook<T = any> {
  state: RemoteState<T>,
  fetchData: () => Promise<void>
}

export function useRemoteData<T = any>(api: () => Promise<ResponseDataType<T>>): RemoteHook<T>
export function useRemoteData<T = any, R = any>(api: (params: R) => Promise<ResponseDataType<T>>): RemoteHookWithParams<T, R>
export function useRemoteData (api: any) {
  const state: RemoteState = reactive({
    data: undefined,
    isLoading: false
  })

  const fetchData = async (params?: any) => {
    state.isLoading = true
    const response = await api(params)
    state.isLoading = false
    if (response.code === 0) {
      state.data = response.data
    }
  }

  return {
    state,
    fetchData
  }
}
